import CheckBox from './check_box';
import { SubjectComponent } from '../core/subject';
const { ccclass, property } = cc._decorator;

@ccclass
export class RadioGroup extends SubjectComponent {
    cbs: CheckBox[] = [];
    _curIndex = -1;
    @property
    get curIndex() {
        return this._curIndex;
    }
    setCurIndex(val, noEmit = false) {
        this._curIndex = val;
        if (!noEmit) {
            this.emit("changed", this.curIndex);
        }
        this.refresh();
    }
    @property
    toggle = false;
    protected onLoad(): void {
        this.cbs = this.getComponentsInChildren(CheckBox);
        this.cbs.forEach(cb => {
            cb.on("clicked", this.onClickBox, this);
        });
    }
    onClickBox(cb) {
        let ind = this.cbs.findIndex(ele => ele == cb);
        if (this.curIndex === ind) {
            if (this.toggle) {
                this.setCurIndex(-1);
            }
        }
        else {
            this.setCurIndex(ind);
        }

        this.refresh();
    }

    refresh() {
        this.cbs.forEach((ele, ind) => {
            ele.checked = this.curIndex == ind;
        });
    }
};